#include <iostream>
#include <unistd.h>
#include <string>
#include <pthread.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int tickets = 1000;

void *rountine(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(tickets > 0){
            usleep(1000);
            std::cout << name<< ", get a ticket: " << tickets-- << std::endl;
        }else{
            std::cout << "没有票了," << name << std::endl;
            pthread_cond_wait(&cond, &mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t p1,p2,p3;
    pthread_create(&p1, NULL,rountine, (void*)"thread-1");
    pthread_create(&p2, NULL,rountine, (void*)"thread-2");
    pthread_create(&p3, NULL,rountine, (void*)"thread-3");

     sleep(5); // for test, 5s开始进行让cond成立，唤醒一个线程
    while(true)
    {
        // pthread_cond_signal(&cond);
        // pthread_cond_broadcast(&cond);

        // 临时
        sleep(6);
        pthread_mutex_lock(&mutex);
        tickets += 1000;
        pthread_mutex_unlock(&mutex);
        pthread_cond_broadcast(&cond);
        

    }
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(p3, nullptr);

    return 0;
}